package com.canyou.archives.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.canyou.archives.constants.ConstantStr;
import com.canyou.archives.model.Archives;
import com.canyou.archives.mapper.ArchivesMapper;
import com.canyou.archives.model.ArchivesLog;
import com.canyou.archives.model.dto.*;
import com.canyou.archives.model.po.ArchivesInformationPO;
import com.canyou.archives.model.po.ArchivesPagePO;
import com.canyou.archives.model.po.PageArchivesResponsePO;
import com.canyou.archives.model.vo.PageVO;
import com.canyou.archives.service.ArchivesLogService;
import com.canyou.archives.service.ArchivesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.canyou.archives.util.StrUtils;
import com.canyou.system.model.User;
import com.canyou.system.service.UserService;
import com.canyou.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 设备档案 服务实现类
 * </p>
 *
 * @author canyou
 * @since 2021-12-07
 */
@Service
public class ArchivesServiceImpl extends ServiceImpl<ArchivesMapper, Archives> implements ArchivesService {
    @Autowired
    private ArchivesMapper archivesMapper;
    @Autowired
    private ArchivesLogService archivesLogService;
    @Autowired
    private UserService userService;

    //新增编辑设备
    @Override
    public Boolean saveOrUpdateArchives(@Valid @NotNull(message = "设备分类信息不能为空") ArchivesDTO archivesDTO) {
        Archives archives = new Archives();
        //新增
        if(StringUtils.isNull(archivesDTO.getId())){
            //设备名称不能为空
            if(StringUtils.isEmpty(archivesDTO.getAname())){
                return false;
            }
            if(StringUtils.isNotNull(archivesDTO.getPersonnel())){
                //判断人员id的数据有效性
                User byId1 = userService.getById(archivesDTO.getPersonnel());
                if(StringUtils.isNull(byId1)){
                    return false;
                }
                archives.setDepartment(byId1.getDeptId());//使用人员部门
                archives.setOrganization(byId1.getOrgId());//使用人员组织
                archives.setState(1);//状态直接为使用中
            }
            //组装插入数据
            BeanUtils.copyProperties(archivesDTO, archives);
            //处理图片地址集合,处理为  地址+  ',' +地址
            String s_PictureList = StrUtils.listToString(archivesDTO.getPictureAddress(), ConstantStr.ADDRESSSEGMENTATION);
            archives.setPicture(s_PictureList);
        }else {  //修改
            //根据id查询判断,没有数据就直接返回
            Archives byId = this.getById(archivesDTO.getId());
            if(StringUtils.isNull(byId)){
                return false;
            }
            //封装修改数据
            if(StringUtils.isNotNull(archivesDTO.getCategoryId())){
                byId.setCategoryId(archivesDTO.getCategoryId()); //设备分类id
            }
            if(StringUtils.isNotEmpty(archivesDTO.getNumber())){
                byId.setNumber(archivesDTO.getNumber()); //编号
            }
            if(StringUtils.isNotEmpty(archivesDTO.getAname())){
                byId.setAname(archivesDTO.getAname()); //名称
            }
            if(StringUtils.isNotNull(archivesDTO.getState())){
                byId.setState(archivesDTO.getState()); //使用状态
            }
            if(StringUtils.isNotNull(archivesDTO.getPersonnel())){
                //判断人员id的数据有效性
                User byId1 = userService.getById(archivesDTO.getPersonnel());
                if(StringUtils.isNull(byId1)){
                    return false;
                }
                byId.setPersonnel(byId1.getId()); //使用人员
                byId.setDepartment(byId1.getDeptId());//使用人员部门
                byId.setOrganization(byId1.getOrgId());//使用人员组织
                byId.setState(1);  //状态直接为使用中
            }
            if(StringUtils.isNotNull(archivesDTO.getFinancialRegistration())){
                byId.setFinancialRegistration(archivesDTO.getFinancialRegistration()); //财务状态
            }
            if(StringUtils.isNotEmpty(archivesDTO.getSnNumber())){
                byId.setSnNumber(archivesDTO.getSnNumber()); //sn码
            }
            if(StringUtils.isNotEmpty(archivesDTO.getWarrantyPolicy())){
                byId.setWarrantyPolicy(archivesDTO.getWarrantyPolicy()); //保修政策
            }
            if(StringUtils.isNotNull(archivesDTO.getPurchaseDate())){
                byId.setPurchaseDate(archivesDTO.getPurchaseDate()); //采购日期
            }
            if(StringUtils.isNotNull(archivesDTO.getPurchaseAmount())){
                byId.setPurchaseAmount(archivesDTO.getPurchaseAmount()); //采购金额
            }
            if(StringUtils.isNotEmpty(archivesDTO.getPurchasePlace())){
                byId.setPurchasePlace(archivesDTO.getPurchasePlace()); //采购地点
            }
            if(StringUtils.isNotEmpty(archivesDTO.getPictureAddress())){
                String s_PictureList = StrUtils.listToString(archivesDTO.getPictureAddress(), ConstantStr.ADDRESSSEGMENTATION);
                byId.setPicture(s_PictureList); //设备图片
            }
            //组装插入数据
            BeanUtils.copyProperties(byId, archives);
        }
        //操作插入数据库并返回结果
        boolean b = this.saveOrUpdate(archives);
        if(!b){
            return false;
        }
       if(StringUtils.isNotNull(archivesDTO.getPersonnel())){
           //写入日志
           ArchivesLog archivesLog = new ArchivesLog();  //组装日志
           archivesLog.setArchivesId(archives.getId()); //领用设备id
           archivesLog.setReceiverlId(archives.getPersonnel());  //领用人id
           archivesLog.setSort(4455);              //排序
           archivesLog.setTypeLog(1);              //日志类型为：领用日志
           return archivesLogService.save(archivesLog);
       }
       return true;
    }

    //条件分页查询
    @Override
    public PageVO getPageList(Integer current, Integer pageSize, ArchivesPageDTO archivesPageDTO) {
        //前端传入的条件和分页合并一个类
        ArchivesPagePO pagePO = new ArchivesPagePO();
        if(StringUtils.isNotNull(archivesPageDTO)){
            BeanUtils.copyProperties(archivesPageDTO, pagePO);
        }
        pagePO.setCurrent(current);pagePO.setPagesize(pageSize);
        //调用mapper获得返回值
        long total=archivesMapper.getEquArchivesTotal(pagePO);
        List<PageArchivesResponsePO> records=archivesMapper.getEquArchivesRecords(pagePO);
        //组装data返回
        PageVO page = new PageVO();
        page.setTotal(total);
        page.setRows(records);
        return page;
    }

    //调用逻辑层完成批量启用和禁用设备功能
    @Override
    public boolean updateDisableenabledevice(@Valid @NotNull(message = "设备分类信息不能为空") ChangeArcvhivesStateDTO dea) {
        //如果id集合为空，或者状态值为空
        if(StringUtils.isEmpty(dea.getIds())){
            return false;
        }
        if(StringUtils.isNull(dea.getState())){
            return false;
        }
        //启用设备
        if(1==dea.getState()){
            //循环遍历根据查找设备
             for(Integer id:dea.getIds()){
                 //查不到设备则跳过
                 Archives archives = this.getById(id);
                 if(StringUtils.isNull(archives)){
                     continue;
                 }
                 //若已指定使用人，启用后将设备使用状态更新为“使用中”,state=1
                  if(StringUtils.isNotNull(archives.getPersonnel())){
                       archives.setState(1);
                  }else {
                       //未指定则更新为“空闲”,state=2
                      archives.setState(2);
                  }
                  //更新数据
                  this.updateById(archives);
             }
            return true;
        }
        //停用设备：使用状态更新为“未启用”,state=0
        if(2==dea.getState()){
            //循环遍历根据查找设备
            for(Integer id:dea.getIds()){
                //查不到设备则跳过
                Archives archives = this.getById(id);
                if(StringUtils.isNull(archives)){
                    continue;
                }
                archives.setState(0);
                //更新数据
                this.updateById(archives);
            }
            return true;

        }
        //报废设备：使用状态更新为“报废”,state=4
        if(3==dea.getState()){
            //循环遍历根据查找设备
            for(Integer id:dea.getIds()){
                //查不到设备则跳过
                Archives archives = this.getById(id);
                if(StringUtils.isNull(archives)){
                    continue;
                }
                archives.setState(4);
                //更新数据
                this.updateById(archives);
            }
            return true;
        }
        return false;
    }

    //批量入账设备
    @Override
    public boolean updateRegistrationDevice(@Valid @NotNull(message = "设备分类信息不能为空") ChangeArcvhivesStateDTO dea) {
        //如果id集合为空，或者状态值为空
        if(StringUtils.isEmpty(dea.getIds())){
            return false;
        }
        if(StringUtils.isNull(dea.getState())){
            return false;
        }
        //根据Id集合遍历查询并返回
        for(Integer id:dea.getIds()){
            Archives byId = this.getById(id);
            if(StringUtils.isNull(byId)){
                //查无数据，跳过
                continue;
            }
            //修改为已经入账
            byId.setFinancialRegistration(true);
            this.updateById(byId);
        }
        return true;
    }

    //设备领用
    @Override
    public boolean receiveDevice(Long receiverlId,Long deviceId) {
        //判断设备是否存在或者处于空闲状态
        Archives archives = this.getById(deviceId);
        if(StringUtils.isNull(archives)||2!=archives.getState()){
            return false;
        }
        //判断输入的领用人id
        User user = userService.getById(receiverlId);
        if(StringUtils.isNull(user)){
            return false;
        }
        //写入日志
        ArchivesLog archivesLog = new ArchivesLog();  //组装日志
        archivesLog.setArchivesId(deviceId); //领用设备id
        archivesLog.setReceiverlId(receiverlId);  //领用人id
        archivesLog.setSort(4455);              //排序
        archivesLog.setTypeLog(1);              //日志类型为：领用日志
        boolean b = archivesLogService.save(archivesLog);
        if(!b){
            return false;
        }
        //更改设备状态为:1使用中
        archives.setPersonnel(user.getId());
        archives.setOrganization(user.getOrgId());
        archives.setDepartment(user.getDeptId());
        archives.setState(1);
        this.updateById(archives);
        return true;
    }

    //设备归还
    @Override
    public boolean returnDevice(Long returnId,Long deviceId) {
        //判断设备是否存在或者处于使用中状态
        Archives archives = this.getById(deviceId);
        if(StringUtils.isNull(archives)||1!=archives.getState()){
            return false;
        }
        //判断输入的领用人id
        User user = userService.getById(returnId);
        if(StringUtils.isNull(user)){
            return false;
        }
        //写入日志
        ArchivesLog archivesLog = new ArchivesLog();  //组装日志
        archivesLog.setArchivesId(deviceId); //领用设备id
        archivesLog.setReturnId(returnId);  //领用人id
        archivesLog.setSort(4455);              //排序
        archivesLog.setTypeLog(2);              //日志类型为：归还日志
        boolean b = archivesLogService.save(archivesLog);
        if(!b){
            return false;
        }
        //修改设备为2空闲
        archives.setPersonnel(0L);
        archives.setOrganization(0L);
        archives.setDepartment(0L);
        archives.setState(2);
       return this.updateById(archives);
    }

    //设备维修中报备
    @Override
    public boolean maintainDevice(@Valid @NotNull(message = "设备信息不能为空") DeviceMaintenanceDTO deviceMaintenanceDTO) {
        //维修设备的id不能为空
        if (StringUtils.isNull(deviceMaintenanceDTO.getDeviceId())) {
            return false;
        }
        Archives archives = this.getById(deviceMaintenanceDTO.getDeviceId());
        //查询有无该设备
        if (StringUtils.isNull(archives)) {
            return false;
        }
        ArchivesLog archivesLog = new ArchivesLog();
        //写入维修日志
        archivesLog.setTypeLog(3);  //维修记录
        archivesLog.setSort(4444);
        archivesLog.setArchivesId(deviceMaintenanceDTO.getDeviceId());
        archivesLog.setRemarks(deviceMaintenanceDTO.getRemarks());
        return archivesLogService.save(archivesLog);
    }

    //设备详细信息
    @Override
    public ArchivesInformationDTO getDeviceById(Long deviceId) {
        //获得记录以外的所有信息
        ArchivesInformationPO info= archivesMapper.getArchivesInformationById(deviceId);
        if(StringUtils.isNull(info)){
            return null;
        }
        //批量处理数据copy
        ArchivesInformationDTO archivesInformationDTO = new ArchivesInformationDTO();
        BeanUtils.copyProperties(info, archivesInformationDTO);
        //处理图片
        if(StringUtils.isNotEmpty(info.getPicture())){
            String picture = info.getPicture();
            String[] split = picture.split(",");
            List<String> list = Arrays.asList(split);
            archivesInformationDTO.setPictureAddress(list);
        }
        //处理使用和维修的记录
        QueryWrapper<ArchivesLog> wrapper = new QueryWrapper<>();
        wrapper.eq("archives_id",deviceId);
        wrapper.orderByAsc("type_log");
        List<ArchivesLog> logList = archivesLogService.list(wrapper);
        System.out.println(logList.size());
        if (StringUtils.isNotEmpty(logList)){
            for(ArchivesLog log:logList){
                if(3==log.getTypeLog()){  //填装维修信息
                    archivesInformationDTO.getMaintainLogs().add(log);
                }else{                    //填装使用信息
                    archivesInformationDTO.getRecordLogs().add(log);
                }
            }
        }
        return archivesInformationDTO;
    }

    //设备基本信息Excel导出
    @Override
    public Boolean exportExcel(HttpServletResponse response) {
        return null;
    }


}
